<template>
  <div>
      <el-button type="primary" icon="el-icon-plus" @click="showAddDialog">添加</el-button>
   <el-table :data="trademarkList" border style="width: 100%; margin: 20px 0">
      <el-table-column
        type="index"
        align="center"
        prop="prop"
        label="序号"
        width="80"
      >
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO" width="width">
        <template slot-scope="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 80px; height: 60px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row, $index }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="showUpdateDialog(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteTrademark(row)"
            >删除</el-button
          >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
      background
      @current-change="getTrademarkList"
      @size-change="handleSizeChange"
      style="text-align: center"
      :current-page="page"
      :page-size="limit"
      :total="total"
      :pager-count="7"
      :page-sizes="[3, 5, 10]"
      layout="prev, pager, next, jumper,->,sizes,total"
        >
      </el-pagination>


 <!-- 对话框 -->
    <el-dialog :title="tmForm.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
      <!-- el-form是专门用来收集数据的
      elform都会指定一个对象\
      elform都会有elform的项，一般一项就用来收集一个数据
      -->
            <el-form ref="tmForm" :model="tmForm" style="width: 80%" :rules="rules">
       <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="tmForm.tmName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- 上传组件 -->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">只能上传jpg文件，且不超过2mb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTrademark"
          >确 定</el-button
        >
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "TrademarkList",
  data() {
    var validateTmName = (rule,value,callback) => {
      if(value.length < 2 || value.length > 20){
          callback(new Error('tmName的长度必须在2-20之前'))
      }else{
        callback()
      }
    };
    return {
      page: 1,
      limit: 3,
      total: 0,
      trademarkList: [],

      dialogFormVisible: false,
      // form指定收集数据的位置
      tmForm:{
        tmName:'',
        logoUrl:'',
      },

     rules: {
         tmName: [
          { required: true, message: "品牌名称必须有", trigger: "blur" },
          { validator: validateTmName, trigger: "change" },
        ],

      logoUrl: [{ required: true, message: "请选择品牌LOGO" }],

     } ,

      // imageUrl: "", //拷贝的upload内部的一个动态数据，后期用不用不知道
    };
  },
  mounted() {
    this.getTrademarkList();
  },
  methods: {
    async getTrademarkList(page = 1) {
      this.page = page;
      try {
        const result = await this.$API.trademark.getPageList(
          this.page,
          this.limit
        );
        if (result.code === 200 || result.code === 20000) {
          this.trademarkList = result.data.records;
          this.total = result.data.total;
        }
      } catch (error) {
        this.$message.error("请求获取品牌列表失败" + error.message);
      }
    },
    //修改每页数量的回调
    handleSizeChange(size){
      this.limit = size;
      this.getTrademarkList();
    },

    handleAvatarSuccess(res,file){
      this.tmForm.logoUrl = res.data
    },
    beforeAvatarUpload(file){
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024/124<2;

     if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 点击弹出添加的dialog页面
    showAddDialog(){
      this.dialogFormVisible = true
      // 添加完成取消再次点击添加 数据仍然存在的bug
      this.tmForm = {
        tmName:'',
        logoUrl:''
      }
    },

    showUpdateDialog(row){
      this.dialogFormVisible = true
      this.tmForm = {...row}
    },
   // 点击确定
    addOrUpdateTrademark() {
      // 先做整体验证
      this.$refs.tmForm.validate(async (valid) => {
        if (valid) {
          //获取请求所需要的参数
          let trademark = this.tmForm;
          //对参数进行整理（需要的时候）
          //发请求
          try {
            //成功干啥
            await this.$API.trademark.addOrUpdate(trademark);
            // 提示
            this.$message.success(
              trademark.id ? "修改品牌成功" : "添加品牌成功"
            );
            // 关闭dialog 回到列表页
            this.dialogFormVisible = false;
            // 更新列表数据
            this.getTrademarkList(trademark.id ? this.page : 1);
          } catch (error) {
            //失败干啥
            this.$message.error(
              trademark.id ? "修改品牌失败" : "添加品牌失败" + error.message
            );
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    deleteTrademark(row) {
      this.$confirm(`你确定要删除${row.tmName}吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await this.$API.trademark.delete(row.id);
            this.$message.success("删除品牌成功");
            // 删除成功后要看当前页有几个，如果比1大就停留在当前页，如果只有一个就去到上一页
            this.getTrademarkList(
              this.trademarkList.length > 1 ? this.page : this.page - 1
            );
          } catch (error) {
            this.$message.error("删除品牌失败" + error.message);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    }

  }
}
</script>

<style>
/* 不要加scoped */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

